<template>
	<div>
		<Loading v-if="loading"></Loading>
		<h3 v-else>{{title}}</h3>
		<BookList :list="books" v-if="books.length"></BookList>
		<h1>{{message}}</h1>
		<el-pagination :hide-on-single-page="true" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" :current-page="pageNum"
		:page-sizes="[2,10,20,40]" :page-size="pageSize" layout="total,sizes,prev,pager,next,jumper"
		:total="total"></el-pagination>
	</div>
</template>

<script>
	import BookList from '@/components/BookList'
	import Loading from '@/components/Loading'
	export default{
		name:'Books',
		data() {
			return{
				title:'',
				books:[],
				message:'',
				loading:true,
				total:5,
				pageNum:1,
				pageSize:2
			}
		},
		// 路由守卫
		beforeRouteEnter(to,from,next){
			next(vm=>{
				vm.title = to.meta.title
				let url = vm.setRequestUrl(to.fullPath)
				vm.getBooks(url,vm.pageNum,vm.pageSize)
			})
		},
		// 路由更新前 多次搜索 组件复用时再次请求数据
		beforeRouteUpdate(to){
			let url = this.setRequestUrl(to.fullPath)
			this.getBooks(url,this.pageNum,this.pageSize)
			return true
		},
		components:{
			BookList,
			Loading
		},
		methods:{
			getBooks(url,pageNum,pageSize){
				this.message = ''
				this.axios.get(url,{params:{pageNum,pageSize}}).then(response=>{
					if(response.data.code == 200){
						this.loading = false
						this.books = response.data.data
						this.total = response.data.total
						if(this.$route.name == 'category'){
							this.message = '当前分类下没有图书！'
						}else{
							this.message = '没有搜到匹配的图书！'
						}
					}
				}).catch(error=>console.log(error))
			},
			// 动态设置服务端数据接口请求URL
			setRequestUrl(path){
				let url = path
				if(path.indexOf('/category') != -1){
					url = '/book' + url + '/page'
				}
				return url
			},
			// 修改每页显示条数时重新请求数据
			handleSizeChange(selectedSize){
				this.pageSize = selectedSize
				let url = this.setRequestUrl(this.$route.fullPath)
				this.getBooks(url,this.pageNum,this.pageSize)
			},
			// 当用户切换选择某一页时 重新请求数据
			handleCurrentChange(currentPage){
				this.pageNum = currentPage
				let url = this.setRequestUrl(this.$route.fullPath)
				this.getBooks(url,this.pageNum,this.pageSize)
			}
		}
	}
</script>

<style>
</style>